package 字符串.字符串转整数;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/7/28 15:27
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String str= "-";
        System.out.println(myAtoi(str));
    }

    //未完善
    public static int myAtoi(String s) {
        if (s.length() == 0) {
            return 0;
        }
        s = s.trim();
        StringBuilder sb = new StringBuilder();
        boolean mark = false;
        for (int i = 0; i < s.length(); i++) {
            char tmpChar = s.charAt(i);
            if (!Character.isDigit(tmpChar) && mark == false) {
                if (tmpChar == '-') {
                    sb.append("-");
                } else {
                    sb.append("0");
                }
            } else if(Character.isDigit(tmpChar)){
                mark = true;
                sb.append(tmpChar);
            } else if (!Character.isDigit(tmpChar)) {
                break;
            }
        }
        String res = sb.toString();
        int index = 0;
        for (int i = 0; i < res.length(); i++) {
            char tmpChar = res.charAt(i);
            if (Character.isDigit(tmpChar) && tmpChar != '0') {
                index = i;
                break;
            }
        }
        long value = 0L;
        if (index > 0) {
            if (res.charAt(0) == '-' && index == 1) {
                res = res.substring(1,res.length());
                value = -Long.valueOf(res);
            }
        } else {
            value = Long.valueOf(res);
        }

        if (value >= Integer.MAX_VALUE) {
            value = Integer.MAX_VALUE;
        }else if (value <= Integer.MIN_VALUE) {
            value = Integer.MIN_VALUE;
        }
        return (int)value;
    }


    //牛
    public static int myAtoi2(String str) {
        str = str.trim();
        if (str.length() == 0) return 0;
        if (!Character.isDigit(str.charAt(0))
                && str.charAt(0) != '-' && str.charAt(0) != '+')
            return 0;
        long ans = 0L;
        boolean neg = str.charAt(0) == '-';
        //i 用于表示起始遍历位置
        int i = !Character.isDigit(str.charAt(0)) ? 1 : 0;
        while (i < str.length() && Character.isDigit(str.charAt(i))) {
            ans = ans * 10 + (str.charAt(i++) - '0');
            //提前判断，可以节省效率
            if (!neg && ans > Integer.MAX_VALUE) {
                ans = Integer.MAX_VALUE;
                break;
            }
            if (neg && ans > 1L + Integer.MAX_VALUE) {
                ans = 1L + Integer.MAX_VALUE;
                break;
            }
        }
        return neg ? (int) -ans : (int) ans;
    }
}
